package com.starsea.book.ui.newpage.adapter

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.ViewGroup
import com.starsea.book.base.adapter.ItemViewHolder
import com.starsea.book.base.adapter.RecyclerAdapter
import com.starsea.book.databinding.ItemMsgNewsBinding
import com.starsea.book.ui.newpage.entity.MsgListEntity
import com.starsea.book.ui.newpage.utils.loadNormalImage
import com.starsea.book.ui.widget.recycler.ItemTouchCallback
import com.starsea.book.utils.gone
import com.starsea.book.utils.visible

class MsgListAdapter(
    context: Context,
    var onChanged: ((value: MsgListEntity.List) -> Unit)? = null
) :
    RecyclerAdapter<MsgListEntity.List, ItemMsgNewsBinding>(context),
    ItemTouchCallback.Callback {


    override fun getViewBinding(parent: ViewGroup): ItemMsgNewsBinding {
        return ItemMsgNewsBinding.inflate(inflater, parent, false)
    }

    override fun registerListener(holder: ItemViewHolder, binding: ItemMsgNewsBinding) {
        binding.root.setOnClickListener {
            getItem(holder.layoutPosition)?.let {
                onChanged!!.invoke(it)
            }

        }
    }

    override fun convert(
        holder: ItemViewHolder,
        binding: ItemMsgNewsBinding,
        item: MsgListEntity.List,
        payloads: MutableList<Any>
    ) {
        binding.run {
            val bundle = payloads.getOrNull(0) as? Bundle
            if (bundle == null) {
                tvTitle.text = item.newsTitle
                tvTime.text = item.releaseTime
                tvContent.text = item.newsContent
                if (TextUtils.isEmpty(item.newsImg)) {
                    ivImage.gone()
                } else {
                    ivImage.visible()
                    ivImage.loadNormalImage(mContext = context, item.newsImg ?: "")
                }
            } else {
                bundle.keySet().map {
                    when (it) {
                        "newsContent" -> tvContent.text = item.newsContent
                        "releaseTime" -> tvTime.text = item.releaseTime
                        "newsTitle" -> tvTitle.text = item.newsTitle
                        "newsImg" -> if (TextUtils.isEmpty(item.newsImg)) {
                            ivImage.gone()
                        } else {
                            ivImage.visible()
                            ivImage.loadNormalImage(mContext = context, item.newsImg ?: "")
                        }
                    }
                }
            }
        }
    }
}